﻿using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.Logging;
using SqlSugar;
using SqlsugarService.Domain;
using SqlsugarService.Domain.BOM;
using SqlsugarService.Domain.Craftsmanship;
using SqlsugarService.Domain.InventoryChange;
using SqlsugarService.Domain.Materials;
using SqlsugarService.Domain.Plan;
using SqlsugarService.Domain.QualityInspection;
using SqlsugarService.Domain.Station;
using SqlsugarService.Domain.Team;
using SqlsugarService.Domain.Warehouse;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace SqlsugarService.Infrastructure.DbContext
{
    /// <summary>
    /// SqlSugar数据库上下文（PostgreSQL专用）
    /// </summary>
    public class SqlSugarDbContext : IDisposable
    {
        private readonly IConfiguration _configuration;
        private readonly ILogger<SqlSugarDbContext> _logger;
        private readonly SqlSugarClient _db;

        public SqlSugarDbContext(IConfiguration configuration, ILogger<SqlSugarDbContext> logger)
        {
            _configuration = configuration ?? throw new ArgumentNullException(nameof(configuration));
            _logger = logger ?? throw new ArgumentNullException(nameof(logger));

            var connectionString = _configuration.GetConnectionString("DefaultConnection");
            if (string.IsNullOrEmpty(connectionString))
                throw new InvalidOperationException("数据库连接字符串未配置。");

            _db = new SqlSugarClient(new ConnectionConfig
            {
                ConnectionString = connectionString,
                DbType = DbType.PostgreSQL,
                IsAutoCloseConnection = true,
                InitKeyType = InitKeyType.Attribute,
                // ConfigureExternalServices = new ConfigureExternalServices
                // {
                //     // 可选：自动驼峰转下划线
                //     EntityService = (prop, col) =>
                //     {
                //         col.DbColumnName = UtilMethods.ToUnderLine(col.DbColumnName);
                //     },
                //     // EntityNameService = (type, table) =>
                //     // {
                //     //     table.DbTableName = UtilMethods.ToUnderLine(table.DbTableName);
                //     // }
                // },
                MoreSettings = new ConnMoreSettings
                {
                    // 可选：不区分大小写LIKE
                    EnableILike = true
                }
            });

            // 日志与错误处理
            _db.Aop.OnLogExecuting = (sql, pars) =>
            {
                _logger.LogInformation($"SQL：{sql}");
                if (pars != null && pars.Length > 0)
                    _logger.LogInformation("参数：" + string.Join(", ", pars.Select(p => $"{p.ParameterName}={p.Value}")));
            };
            _db.Aop.OnError = (ex) =>
            {
                _logger.LogError(ex, "SqlSugar执行异常");
            };

            // 兼容时间类型
            AppContext.SetSwitch("Npgsql.EnableLegacyTimestampBehavior", true);
            AppContext.SetSwitch("Npgsql.DisableDateTimeInfinityConversions", true);

            // 根据配置决定是否自动建表
            var enableAutoCreateTables = _configuration.GetValue<bool>("Database:EnableAutoCreateTables", false);
            
            if (enableAutoCreateTables)
            {
                _logger.LogInformation("自动建表功能已启用，开始初始化数据表...");
                InitializeTables();
                _logger.LogInformation("数据表初始化完成");
            }
            else
            {
                _logger.LogInformation("自动建表功能已禁用，跳过表初始化");
            }



        }

        public SqlSugarClient Db => _db;

        /// <summary>
        /// 初始化所有数据表
        /// </summary>
        private void InitializeTables()
        {
            var entityTypes = new[]
            {
                typeof(Users),
                typeof(BomInfo),
                typeof(BomItem),
                typeof(ProcessRouteEntity),
                typeof(ProcessRouteStep),
                typeof(ProcessStep),
                typeof(ProcessStepProduct),
                typeof(SalesOutboundDetailEntity),
                typeof(SalesOutboundEntity),
                typeof(MaterialCategory),
                typeof(MaterialEntity),
                typeof(ProcessStepMaterial),
                typeof(ProductEntity),
                typeof(ProductionOrder),
                typeof(ProductionPlan),
                typeof(WorkOrderTaskEntity),
                typeof(InspectionItemEntity),
                typeof(QualityInspectionPlanEntity),
                typeof(QualityPlanInspectionItemLink),
                typeof(WorkReportInspectionEntity),
                typeof(EquipmentEntity),
                typeof(StationEntity),
                typeof(ToolCategoryEntity),
                typeof(ToolEntity),
                typeof(TeamEntity),
                typeof(TeamMemberEntity),
                typeof(InventoryOrderEntity),
                typeof(TransferOrderEntity),
                typeof(WarehouseAreaEntity),
                typeof(WarehouseEntity),
                typeof(WarehouseLocationEntity),
                typeof(ProcessStepMaterialDetail),
                typeof(Salesorder),
                typeof(QualityInspectionPlanWorkReportEntity),
                typeof(Dispatchwork),
            };

            var createMode = _configuration.GetValue<string>("Database:CreateMode", "IfNotExists");
            _logger.LogInformation($"表创建模式: {createMode}");

            int createdCount = 0;
            int existingCount = 0;
            int skippedCount = 0;
            
            foreach (var entityType in entityTypes)
            {
                try
                {
                    var tableName = _db.EntityMaintenance.GetTableName(entityType);
                    
                    switch (createMode.ToLower())
                    {
                        case "always":
                            // 总是创建表（会删除重建）
                            _db.CodeFirst.InitTables(entityType);
                            _logger.LogInformation($"表 {tableName} ({entityType.Name}) 已重新创建");
                            createdCount++;
                            break;
                            
                        case "ifnotexists":
                        default:
                            // 仅在表不存在时创建
                            if (!_db.DbMaintenance.IsAnyTable(tableName))
                            {
                                _db.CodeFirst.InitTables(entityType);
                                _logger.LogInformation($"表 {tableName} ({entityType.Name}) 不存在，已创建");
                                createdCount++;
                            }
                            else
                            {
                                _logger.LogDebug($"表 {tableName} ({entityType.Name}) 已存在，跳过创建");
                                existingCount++;
                            }
                            break;
                            
                        case "never":
                            // 从不创建表
                            _logger.LogDebug($"表创建模式为Never，跳过 {tableName} ({entityType.Name})");
                            skippedCount++;
                            break;
                    }
                }
                catch (Exception ex)
                {
                    _logger.LogError(ex, $"表 {entityType.Name} 处理失败: {ex.Message}");
                }
            }

            // 输出统计信息
            _logger.LogInformation($"表初始化统计 - 创建: {createdCount}, 已存在: {existingCount}, 跳过: {skippedCount}");
        }

        public void Dispose()
        {
            _db?.Dispose();
        }
    }
}
